#include "Configuration.h"

Configuration *Configuration::_instance = nullptr;

Configuration *Configuration::getInstance() {
    if (_instance == nullptr) {
        _instance = new Configuration();
    }
    return _instance;
}

void Configuration::deleteInstance() {
    if (_instance) {
        delete _instance;
        _instance = nullptr;
    }
}

void Configuration::setConfigMap(const string &conf_file) {
    ifstream file(conf_file);
    string line;
    string currentSection;

    while (getline(file, line)) {
        // 忽略空行和注释
        if (line.empty() || line[0] == '#' || line[0] == ';') {
            continue;
        }

        // 解析节（section）
        if (line[0] == '[') {
            size_t endPos = line.find(']');
            if (endPos != string::npos) {
                currentSection = line.substr(1, endPos - 1);
            }
        } else {
            // 解析键值对
            size_t eqPos = line.find('=');
            if (eqPos != string::npos) {
                string key = line.substr(0, eqPos - 1);
                string value = line.substr(eqPos + 2);
                _configMap[currentSection + "." + key] = value;
            }
        }
    }
}

// 获取指定配置项的值，返回字符串类型
string Configuration::get(const string &section, const string &key) const {
    string fullKey = section + "." + key;
    auto it = _configMap.find(fullKey);
    if (it != _configMap.end()) {
        return it->second;
    } else {
        std::cerr << "Config key not found: " << fullKey << "\n";
        return NULL;
    }
}

void Configuration::print() const {
    for (auto &ele : _configMap) {
        std::cout << ele.first << " " << ele.second << "\n";
    }
}

Configuration::Configuration() {};
Configuration::~Configuration() {};